package com.markdown.markdown;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Instant;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Markdown 网络图片下载器
 */
public class MarkdownImgDownloader {
    // 源 markdown 仓库目录
    private static final Path SOURCE_VAULT_PATH = Paths.get("D:\\BaiduSyncdisk\\小程序与公众号\\程序员Ink公众号\\weixin-article\\articles");

    // 目标 markdown 仓库目录，注意不要放到目标目录下，否则会递归遍历导致死循环
    private static final Path
            TARGET_VAULT_PATH =
            Paths.get("D:\\BaiduSyncdisk\\小程序与公众号\\程序员Ink公众号\\weixin-article\\articles-local");

    // 资源目录名称(与 md 目标文件同层级,存储离线图片)
    private static final String ASSETS_DIRECTORY_NAME = "assets";

    // 简单日志记录
    private static final String
            LOG_FILE =
            TARGET_VAULT_PATH.getParent() + File.separator + "log_" + Instant.now().getEpochSecond() + ".txt";

    private static final ArrayList<String>
            ERROR_STR = new ArrayList<>();

    private static int MD_COUNT, IMG_COUNT, ERROR_COUNT;

    /**
     * 配置 markdown 仓库源和目标目录；
     * 遍历源仓库,复制目录结构和 md 文件到目标仓库;
     * 每个 md 文件同级新建 assets 文件夹,assets 下新建 md 文件同名的文件夹用以存放离线图片；
     */

    /**
     * 程序的入口点，负责启动文件处理流程，并记录整体流程的开始和结束时间
     *
     * @param args 命令行参数，未在此方法中使用
     */
    public static void main(String[] args) {
        // 记录开始时间
        long startTime = Instant.now().getEpochSecond();
        log(">>>>> ALL_START:" + startTime);

        try {
            // 确保目标目录存在
            Files.createDirectories(TARGET_VAULT_PATH);

            // 遍历源目录树，对每个文件和目录进行处理
            Files.walkFileTree(SOURCE_VAULT_PATH, new SimpleFileVisitor<Path>() {
                /**
                 * 在访问目录中的文件之前，先处理目录本身
                 *
                 * @param dir   当前访问的目录
                 * @param attrs 目录的属性信息
                 * @return 指示是否继续遍历或跳过子树
                 */
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
                    // 计算目标目录路径
                    Path
                            targetPath =
                            TARGET_VAULT_PATH.resolve(SOURCE_VAULT_PATH.relativize(dir).toString());
                    try {
                        // 创建对应的目标目录
                        boolean exists = Files.exists(targetPath);
                        if (!exists) {
                            Files.createDirectories(targetPath);
                        }
                        System.out.println("访问目录：" + targetPath);
                    } catch (IOException e) {
                        e.printStackTrace();
                        // 如果创建目录失败，跳过该目录下的所有文件
                        return FileVisitResult.SKIP_SUBTREE;
                    }
                    return FileVisitResult.CONTINUE;
                }

                /**
                 * 处理文件，主要是复制Markdown文件并下载其中的图片
                 *
                 * @param file  当前访问的文件
                 * @param attrs 文件的属性信息
                 * @return 指示是否继续遍历
                 */
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                    // 仅处理Markdown文件
                    if (file.toString().endsWith(".md")) {
                        // 计算目标Markdown文件路径
                        Path
                                targetMdPath =
                                TARGET_VAULT_PATH.resolve(SOURCE_VAULT_PATH.relativize(file).toString());
                        try {
                            if (Files.exists(targetMdPath)){
                                System.out.println(">>>>> " + targetMdPath + " exists, skip");
                                return FileVisitResult.CONTINUE;
                            }
                            // 复制Markdown文件到目标位置，并替换已存在的文件
                            Files.copy(file, targetMdPath, StandardCopyOption.REPLACE_EXISTING);
                            // 复制到目标文件夹后，下载图片并替换Markdown中的URL为本地路径
                            downloadAndTransImgUrlToLocal(targetMdPath.toFile());
                            // 记录处理的Markdown文件数量
                            MD_COUNT += 1;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                    System.err.println("访问文件失败：" + file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    System.out.println("完成目录访问：" + dir);
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 记录结束时间，并计算总耗时
        log(">>>>> ALL FINISH! COST TIME:" + (Instant.now().getEpochSecond() - startTime));
        // 输出处理的Markdown文件数量
        log(">>>>> MD_COUNT:" + MD_COUNT);
        // 输出处理的图片数量
        log(">>>>> IMG_COUNT:" + IMG_COUNT);
        // 输出错误数量
        log(">>>>> ERROR_COUNT:" + ERROR_COUNT);
        // 输出所有错误信息
        ERROR_STR.stream().map(s -> ">>>>> ERROR_INFO:" + s).forEach(MarkdownImgDownloader::log);
    }

    /**
     * md 文件网络图片下载和替换为本地路径
     *
     * @param mdFile markdown文件
     */
    public static void downloadAndTransImgUrlToLocal(File mdFile) {
        try {
            Path
                    asertsDir =
                    Paths.get(mdFile.getParent() + File.separator + ASSETS_DIRECTORY_NAME +
                              File.separator +
                              mdFile.getName().substring(0, mdFile.getName().lastIndexOf(".")));
            if (Files.notExists(asertsDir)) {
                Files.createDirectories(asertsDir);
            }
            String mdContent = readMdContent(mdFile);
            ArrayList<String> imgUrls = extractUrls(mdContent);
            if (imgUrls.isEmpty()) {
                log(mdFile.getPath() + "\t #doesn't have image URL");
                return;
            }
            for (String imgUrl : imgUrls) {
                String imgName = imgUrl.substring(imgUrl.lastIndexOf("/") + 1);
                String imgLocalUrl = asertsDir + File.separator + imgName;
                getAndSaveImg(imgUrl, new File(imgLocalUrl));
                Path imgLocalPath = Paths.get(imgLocalUrl);
                Path mdFilePath = Paths.get(mdFile.getPath());
                Path
                        relativize =
                        mdFilePath.getParent().relativize(imgLocalPath);
                mdContent = mdContent.replace(imgUrl, relativize.toString().replace("\\", "/"));
                log(imgUrl + "\t" + imgLocalPath + "\t" + relativize);
            }
            FileWriter
                    fileWriter = new FileWriter(mdFile);
            fileWriter.write(mdContent);
            fileWriter.close();
        } catch (Exception e) {
            ERROR_COUNT += 1;
            ERROR_STR.add(mdFile.getPath() + "\t" + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 读取 md文件内容     *     * @param mdFile markdown文件     * @return md文件内容
     */
    public static String readMdContent(File mdFile) {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream(mdFile), StandardCharsets.UTF_8))) {
            String line;
            while ((line = bf.readLine()) != null) {
                sb.append(line).append(System.lineSeparator());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 解析出图片 url
     *
     * @param content md文本(源 md 文本使用 html 的 <img> 标签 src 属性引用图片)
     * @return 提取 src 属性值
     */
    public static ArrayList<String> extractUrls(String content) {
        ArrayList<String> imgUrls = new ArrayList<>();
        //        String imgSrcEx = "src=\"(https?:\\S+.(jpg|jpeg|png|gif|webp|bmp|tiff|svg))\"";
        String imgSrcEx = "!\\[(.*?)\\]\\(https://[^\\s]+(.jpg|.jpeg|.png|.svg|.gif|.webp|.bmp|.tiff)\\)";
        Pattern compile = Pattern.compile(imgSrcEx);
        Matcher
                matcher = compile.matcher(content);
        while (matcher.find()) {
            String group = matcher.group(0);
            String replace = group.replaceFirst("!\\[(.*?)\\]\\(", "").replaceFirst("\\)", "");
            System.out.println(replace);

            imgUrls.add(replace);
        }
        return imgUrls;
    }

    /**
     * 下载网络图片保存到本地     *     * @param imgUrl        网络图片 url     * @param targetImgFile 待保存为的图片文件     * @throws IOException 请求失败,非正常200响应
     */

    public static void getAndSaveImg(String imgUrl, File targetImgFile) throws Exception {
        URL url = new URL(imgUrl);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0");
        httpConn.setInstanceFollowRedirects(false);
        int responseCode = httpConn.getResponseCode();
        if (responseCode >= 300 && responseCode < 400) {
            String redirectUrl = httpConn.getHeaderField("Location");
            if (redirectUrl != null) {
                getAndSaveImg(redirectUrl, targetImgFile);
                return;
            }
        }
        if (responseCode == HttpURLConnection.HTTP_OK) {
            try (InputStream inputStream = httpConn.getInputStream(); FileOutputStream outputStream = new FileOutputStream(targetImgFile)) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.flush();
            } finally {
                httpConn.disconnect();
            }
        } else {
            throw new Exception(targetImgFile.getPath() + "\t" + imgUrl +
                                "Failed to download image. HTTP error code: " + responseCode);
        }
        IMG_COUNT += 1;
    }

    /**
     * 简单日志输出保存     *     * @param message 日志信息
     */
    public static void log(String message) {
        FileWriter writer = null;
        try {
            writer = new FileWriter(LOG_FILE, true);
            writer.write(message);
            writer.write(System.lineSeparator());
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}